import axios from 'axios'

// axios基本配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://demo.vuetp.com/'
const qs = require('qs')

// http request 拦截器
axios.interceptors.request.use(
  config => {
    const authkey = localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')).auth_key : ''
    config.data = qs.stringify(config.data)
    if (authkey) {
      config.headers.AuthKey = authkey
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    // 0为success状态码 100代表授权失败
    switch (response.data.state) {
      case 0:
        return response.data
      case 100:
        window.vm.$Modal.error({
          title: '提醒',
          content: '登录失效',
          onOk: () => {
            let m = response.data.data
            window.router.push('/' + m + '/login')
            setTimeout(() => {
              window.router.go(0)
            }, 300)
          }
        })
        break
      default:
        window.vm.$Message.error({
          content: response.data.mess
        })
    }
  },
  error => {
    return Promise.reject(error)
  })

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post (url, data) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * get 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get (url, data) {
  return new Promise((resolve, reject) => {
    axios.get(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * put 请求方法
 * @param url
 * @param id
 * @param data
 * @returns {Promise}
 */
export function put (url, id, data) {
  return new Promise((resolve, reject) => {
    axios.put(url + id, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * delete 请求方法
 * @param url
 * @param id
 * @returns {Promise}
 */
export function _delete (url, id) {
  return new Promise((resolve, reject) => {
    axios.delete(url + id)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

export default axios
